<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCate()"> 添加分类 </el-button>
        </el-col>
      </el-row>

      <!-- 表格区 -->

      <tree-table
        class="treeTable"
        :data="cateList"
        :columns="columns"
        border
        :selection-type="false"
        show-index
        index-text="#"
        :expand-type="false"
      >
        <template slot="isOk" slot-scope="scope">
          <!-- 是否有效 -->
          <i
            class="el-icon-success"
            style="color: lightgreen"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="warning"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="danger" size="mini" v-else>三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCate(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClose()"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- :options 绑定的数据 -->
          <!-- ：prop 用来指定配置对象 -->
          <!-- change 当选择的数据该改变了 -->
          <el-cascader
            v-model="selectKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateDialog()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击编辑  弹出对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="eidtCateDialogVisible"
      width="50%"
    >
      <el-form ref="editCateformRef" :model="editCateform" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="editCateform.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidtCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eidtCateDialog()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      // 商品分类数据列表
      cateList: [],
      // 总数据条数
      total: 0,
      //   为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isOk",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      //   点击添加分类 控制对话框展示与否
      addCateDialogVisible: false,
      //   添加分类的表单数据对象
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      //   添加分类的验证规则对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 父级分类的列表
      parentCateList: [],
      // 配置对象
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      //  保存数据中id
      selectKeys: [],
      // 编辑是否弹出对话框
      eidtCateDialogVisible: false,
      // 储存表单内容
      editCateform: {},
    };
  },

  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$Message.error("商品分类数据列表获取失败");
      }
      this.$Message.success("获取商品分类列表获取成功");
      //  console.log("32123");
      console.log(res.data);
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    // 监听pagesie改变
    handleSizeChange(newPage) {
      this.queryInfo.pagesize = newPage;
      // 刷新数据
      this.getCateList();
    },
    // 监听pagenum变化
    handleCurrentChange(newNum) {
      this.queryInfo.pagenum = newNum;
      this.getCateList();
    },
    // 监听添加用户按钮
    addCate() {
      // 先获取父级两级数据
      this.getParentCateList();
      // 再显示对话框
      this.addCateDialogVisible = true;
    },
    // 获取父集分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$Message.error("获取父级分类失败");
      }
      this.$Message.success("获取父级分类成功");
      console.log(res);
      this.parentCateList = res.data;
    },
    // 监听添加分类，父集分类改变
    parentCateChanged() {
      console.log(this.selectKeys);
      if (this.selectKeys.length > 0) {
        // 确定父级分类的id
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1];
        // 为当前分类登记赋值
        this.addCateForm.cat_level = this.selectKeys.length;
        return;
      } else {
        // 父级分类的id
        this.addCateForm.cat_pid = 0;
        // 父级分类的等级
        this.addCateForm.cat_level = 0;
      }
    },
    // 点击按钮添加分类
    addCateDialog() {
      console.log(this.addCateForm);
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) return this.$Message.error("添加分类失败");
        this.$Message.success("添加分类成功");
      });
      this.getCateList();
      this.addCateDialogVisible = false;
    },
    // 点击取消隐藏对话框,重置表单数据
    addCateDialogClose() {
      this.$refs.addCateFormRef.resetFields();
      this.selectKeys = [];
      this.cat_pid = 0;
      this.cat_level = 0;
      this.addCateDialogVisible = false;
    },
    // 监听编辑按钮
    async editCate(id) {
      const { data: res } = await this.$http.get("categories/" + id);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$Message.error("获取id失败");
      }
      this.$Message.success("获取id成功");
      this.editCateform = res.data;
      this.eidtCateDialogVisible = true;
    },
    //  监听编辑按钮 点击确定事件
    eidtCateDialog() {
      this.$refs.editCateformRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "categories/" + this.editCateform.cat_id,
          { cat_name: this.editCateform.cat_name }
        );
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$Message.error("编辑提交信息失败");
        }
        this.$Message.success("编辑提交信息成功");
        // 先刷新数据
        this.getCateList();
        this.eidtCateDialogVisible = false;
      });
    },
    // 监听删除时间
    async deleteCate(id) {
     const delConfig =  await this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(err => err)
      // console.log(delConfig);
      if(delConfig!=="confirm")
      return this.$Message.info("您取消了删除操作！")
      const {data:res} = await this.$http.delete('categories/'+id)
      console.log(res);
      if(res.meta.status!==200){
        return this.$Message.error("删除分类失败")
      }
      this.$Message.success("删除分类成功")
              // 先刷新数据
        this.getCateList();
        this.eidtCateDialogVisible = false;
    },
  },
};
</script>

<style scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>